<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search
      ref="customSearchRef"
      v-slot="{ params }"
      :default-params="{ type: defaultStatus, cjsj: [], isCompletion: defaultCompletion }"
      @submit="handleSeachTable"
    >
       <t-col :span="3">
        <t-form-item label="楼盘名称" name="propertyName">
          <t-select v-model:value="params.propertyName" clearable filterable placeholder="">
            <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
              {{ _.name }}
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="详细地址" name="address">
          <t-input v-model:value="params.address" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="对接人" name="receiverId" >
        <t-cascader
          v-model:value="params.receiverId"
          :options="sendersTree"
          :keys="{ value: 'id', label: 'name' }"
          placeholder=""
          filterable
          clearable
        />
      </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="cjsj">
          <t-date-range-picker
            allow-input
            v-model:value="params.cjsj"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
            @change="
              (value) => {
                const [beginTime, endTime] = value;
                params.beginTime = beginTime;
                params.endTime = endTime;
              }
            "
          />
        </t-form-item>
      </t-col>

      
      
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :key="`table-${defaultStatus}`"
      :columns="defaultStatus=='1'?columnsType:columns"
      :api="productMessageCRUD.page"
      column-controller-key="interactionList"
    >
      <template #topContent>
        <div style="display: flex;justify-content: space-between; align-items: center;">
          <!-- 新建情况 -->
          <t-button
            v-permission="['system:product-message:create']"
            @click="handleOpenDialog('create', { imageUrl:[], type:defaultStatus})"
          >
            新建情况
          </t-button>

          <t-radio-group v-model="defaultStatus" theme="button" @change="handleStatusChange">
            <t-radio-button :value="_.id" v-for="_ in [
              {name:'下单',id:'1'},
              {name:'售后',id:'2'},
              ]">{{ _.name }}</t-radio-button>
           </t-radio-group>
        </div>
        <t-tabs v-model:value="defaultCompletion" :list="list" @change="handleCompletionChange" style="margin-bottom: var(--td-comp-margin-xxl)"/>
      </template>
      <template #engineeringId="{ row }">
        {{ orderPersonList.find((item) => item.id === row.engineeringId)?.customerName }}
        {{ propertyInfoList.find((item) => item.id == row.propertyName)?.name }} 
        <span style="color: gray;">{{ row.address }}</span>
      </template>
      
      <template #senders="{ row }">
        {{(JSON.parse(row.senders).map((id: any)=>userStore.getUserNameById(id))).join('、')}}
      </template>
      <template #readUser="{ row }">
        {{row.readUser&&(JSON.parse(row.readUser).map((id: any)=>userStore.getUserNameById(id))).join('、')}}
      </template>
      <template #receiverId="{ row }">
        {{ userStore.getUserNameById(row.receiverId) }}
      </template>
      <template #creator="{ row }">
        {{ userStore.getUserNameById(row.creator) }}
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #placeAnOrderTime="{ row }">
        {{ row.placeAnOrderTime&&dayjs(row.placeAnOrderTime).format('YYYY-MM-DD') }}
      </template>
      <template #acceptanceCheckTime="{ row }">
        {{ row.acceptanceCheckTime&&dayjs(row.acceptanceCheckTime).format('YYYY-MM-DD') }}
      </template>
      
      <template #operation="{ row }">
        <t-space break-line>
           <t-link theme="primary" @click="handleOpenDialog('read', { id: row.id })"> 详情 </t-link>
           <t-link theme="primary" @click="handleOpenDialog('update', { id: row.id })"  v-permission="['system:product-message:update']" v-if="row.isCompletion!='1'"> 编辑 </t-link>
          <t-popconfirm content="确认已解决该工地吗？" @confirm="handleDelete({ id: row.id })" v-if="row.isCompletion!='1'">
            <t-link theme="danger"> 已解决 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly, mode }"
      :api-map="productMessageCRUD"
      header="*情况"
      width="35%"
      :on-before-save-data="handleDialogSaveData"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      
      <t-form-item label="对接人" name="receiverId" :rules="[{ required: true, message: '请输入对接人' }]">
        <t-cascader
          v-model:value="formData.receiverId"
          :options="sendersTree"
          :keys="{ value: 'id', label: 'name' }"
          placeholder=""
          filterable
          clearable
        />
      </t-form-item>
      <t-form-item label="关联工地" name="productOrderId" :rules="[{ required: true, message: '请选择关联工地' }]">
        <t-select v-model:value="formData.productOrderId" clearable :filter="filterMethod" placeholder="">
            <t-option v-for="_ in orderPersonList" :key="_.id" :value="_.id" :label="_.customerName">
              {{ _.customerName }}
              {{ propertyInfoList.find((item) => item.id === _.propertyName)?.name }} 
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
      </t-form-item>
      <t-form-item label="工厂" name="factory" :rules="[{ required: true, message: '请输入工厂' }]">
        <t-input v-model:value="formData.factory" placeholder="请输入工厂" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="问题" name="problem" :rules="[{ required: true, message: '请输入问题' }]">
        <t-input v-model:value="formData.problem" placeholder="请输入问题" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="反馈" name="feedback" :rules="[{ required: true, message: '请输入反馈' }]">
        <t-input v-model:value="formData.feedback" placeholder="请输入反馈" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="台面" name="countertop" :rules="[{ required: false, message: '请输入台面' }]" v-if="formData.type=='1'">
        <t-input v-model:value="formData.countertop" placeholder="请输入台面" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="水槽" name="basin" :rules="[{ required: false, message: '请输入水槽' }]" v-if="formData.type=='1'">
        <t-input v-model:value="formData.basin" placeholder="请输入水槽" clearable :readonly="readonly" />
      </t-form-item>
       <t-form-item label="类型" name="type" :rules="[{ required: true, message: '请选择类型' }]">
        <t-radio-group v-model:value="formData.type" clearable :readonly="readonly" placeholder="" :options="[
            {label:'下单',value:'1'},
            {label:'售后',value:'2'},
            ]">
        </t-radio-group>
      </t-form-item>

      <t-form-item label="图片/文件" name="imageUrl" >
        <upload2 v-model:files="formData.imageUrl" />
      </t-form-item>

      
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'NoticeProduc',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { computed, onMounted, onUpdated, Ref, ref, useTemplateRef, nextTick } from 'vue';

import { propertyManageCRUD } from '@/api/config/property';
import { endProduct, productMessageCRUD } from '@/api/notice/product';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import disposableParams from '@/utils/disposableParams';
import Upload2 from '@/components/upload/index2.vue';
import { getSimpleDeptList } from '@/api/system/dept';
import listToTree from '@/utils/listToTree';
import { getSimpleUserList } from '@/api/system/user';
import { engineeringListCRUD } from '@/api/project/engineering';
import { productOrderCRUD } from '@/api/order/product';

// 用户仓库
const userStore = useUserStore();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
      handleGetOrderPersonList();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();

// 人员列表
const orderPersonList = ref([])
// 处理获取楼盘信息列表
const handleGetOrderPersonList = () => {
  const params = {
    pageSize: 99999,
    pageNo:1,
  };
  productOrderCRUD.page(params)
    .then((data) => {
      orderPersonList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
const list = [{
  label:'未解决', value: 0
},{
  label:'已解决', value: 1
}]
const defaultCompletion = ref(0)
// 订单信息过滤搜索 搜到地址
const filterMethod = (inputValue: string, option: any) => {
  // 根据 option.value 找到原始数据项
  const originalItem = orderPersonList.value.find(item => item.id === option.value);
  if (!originalItem) return false;
  
  // 创建搜索字符串（包含名称和地址）
  const searchString = `${originalItem.customerName} ${originalItem.address}`.toLowerCase();
  return searchString.includes(inputValue.toLowerCase());
};

// 默认状态
const defaultStatus = ref('1')
// 状态改变
const handleStatusChange = async() => {
  customSearchRef.value.params.type = defaultStatus.value
  customSearchRef.value.params.isCompletion = defaultCompletion.value
  await nextTick()
  handleInitTable()
}
// 解决改变
const handleCompletionChange = () => {
  customSearchRef.value.params.type = defaultStatus.value
  customSearchRef.value.params.isCompletion = defaultCompletion.value
  handleInitTable()
}
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'creator', title: '发起人', width: 80 },
  { colKey: 'receiverId', title: '对接人', width: 80 },
  { colKey: 'engineeringId', title: '工地' },
  { colKey: 'factory', title: '工厂', width: 60 },
  { colKey: 'problem', title: '问题' },
  // { colKey: 'imageUrl', title: '图片' },
  { colKey: 'feedback', title: '反馈'},
  { colKey: 'placeAnOrderTime', title: '下单时间',  width: 100 },
  // { colKey: 'acceptanceCheckTime', title: '验收时间',  width: 100 },
  { colKey: 'createTime', title: '发起时间', width: 160 },
  { colKey: 'operation', title: '操作', width: 150, fixed: 'right' },
];
const columnsType: TableCol[] = [
  { colKey: 'creator', title: '发起人', width: 70 },
  { colKey: 'receiverId', title: '对接人', width: 70 },
  { colKey: 'engineeringId', title: '工地' },
  { colKey: 'factory', title: '工厂', width: 60 },
  { colKey: 'problem', title: '问题' },
  // { colKey: 'imageUrl', title: '图片' },
  { colKey: 'feedback', title: '反馈'},
  { colKey: 'countertop', title: '台面', width:110 },
  { colKey: 'basin', title: '水槽',width:100 },
  { colKey: 'placeAnOrderTime', title: '下单时间', width: 100 },
  // { colKey: 'acceptanceCheckTime', title: '验收时间', width: 100 },
  { colKey: 'createTime', title: '发起时间', width: 160 },
  { colKey: 'operation', title: '操作', width: 148, fixed: 'right' },
];
const handleSeachTable=(params:any) =>{
  disposableParams.set('to-do-tree-jump-params', {
    orderIds: '',
  });
  customSearchRef.value.params.type = defaultStatus.value
  customSearchRef.value.params.isCompletion = defaultCompletion.value
  handleInitTable()
}
// 处理初始化表格
const handleInitTable = () => {
  // 待办树跳转参数
  const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
  const params = {
    orderIds: toDoTreeJumpParams.orderIds,
    ...customSearchRef.value.params,
    type:defaultStatus.value
  };
  if (!params.cjsj.length) {
    delete params.beginTime;
    delete params.endTime;
  }
  customTableRef.value.initTable(params);
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
 params.imageUrl = JSON.parse(params.imageUrl)
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
interface userTreeData {
  id: string | number;       // 节点唯一标识（可能是用户ID或部门ID）
  deptId?: string | number;  // 部门ID（仅部门节点可能有）
  name: string;             // 节点显示名称（部门名或用户名）
  parentId: string | number; // 父节点ID（用于构建树形结构）
  children?: userTreeData[]; // 子节点（`listToTree` 可能会自动添加）
}
const sendersTree = ref([])
const handleGetUserTree = () => {
  Promise.all([getSimpleDeptList(),getSimpleUserList()])
  .then((res) => {
    const arr: userTreeData[] = []
    console.log(res,'pp');
    
    res[0].forEach((item: any) => {
      arr.push({
        id: `dept_${item.id}`,
        deptId:`dept_${item.id}`,
        name: item.name,
        parentId: item.parentId?`dept_${item.parentId}`:'',
      });
    });
    res[1].forEach((item: any) => {
      arr.push({
        id:item.id,
        name:item.nickname,
        parentId: item.deptId?`dept_${item.deptId}`:'',
      })
    })
    sendersTree.value = listToTree(arr, 'deptId').filter(item => item.id === 'dept_100')
  })
  .catch(() => {
    sendersTree.value = []
  })
}
handleGetUserTree()
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable()
})


// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  const hasWaitingFiles = params.imageUrl.some((item: any) => item.status === 'waiting');
  if (hasWaitingFiles) {
    MessagePlugin.warning('有文件待上传，请点击上传文件');
    return false;
  }
  if (params.productOrderId) {
    const selectedEngineering = orderPersonList.value.find(
      item => item.id === params.productOrderId
    );
    if (selectedEngineering) {
      params.engineeringId = selectedEngineering.engineeringId;
      params.orderId = selectedEngineering.orderId;
    }
  }
  return params;
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理已解决
const handleDelete = (params: Record<string, any>) => {
  endProduct(params)
    .then(() => {
      MessagePlugin.success('工地已解决');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
</script>
<style lang="less" scoped>
:deep(.t-radio-group .t-radio-button) {
  border: none;
  border-radius: 18px !important;
  margin-left: 11px;
}

:deep(.t-radio-group .t-radio-button.t-is-checked) {
  background-color: #f2f3f5;
}
</style>
